package com.uxsino.rule.nms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.uxsino.commons.db.redis.RedisKeys;
import com.uxsino.commons.db.redis.impl.AbstractRedisRepostory;
import com.uxsino.rule.nms.model.RedisFlapInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;

@Component
public class FlapInfoRedisService extends AbstractRedisRepostory<String> {

    @Autowired
    private HashOperations<String, String, String> hashOperations;

    @Override
    protected TypeReference<String> getSerializeClass() {
        return new TypeReference<String>(){};
    }

    @Override
    public String getRedisKey() {
        return RedisKeys.PATTEN_KEY_FLAPINFO;
    }

    @Override
    public List<String> getAll() {
        List<String> datas = new ArrayList<>();
        List<String> origins = hashOperations.values(getRedisKey());
        if(origins == null){
            return datas;
        }
        origins.parallelStream().forEach(itm->{
            datas.add(JSON.toJSONString(itm));
        });
        return datas;
    }

    public Long increment(String alertCode, Long flap, Long ruleId, String compName) {
        RedisFlapInfo flapInfo = getRedisFlapInfo(alertCode);
        if (flapInfo == null ) {
            flapInfo = new RedisFlapInfo();
            flapInfo.setTimes(1L);
        }else {
            flapInfo.setTimes(flapInfo.getTimes() + 1);
        }
        flapInfo.setFlap(flap);
        flapInfo.setCompName(compName);
        flapInfo.setRuleId(ruleId);
        flapInfo.setAlertCode(alertCode);
        put(alertCode, JSON.toJSONString(flapInfo));
        return flapInfo.getTimes();
    }


    public Long getTimes(String alertCode) {
        RedisFlapInfo info = getRedisFlapInfo(alertCode);
        if (info == null) {
            return null;
        } else {
            return info.getTimes();
        }
    }

    public void setFlap(String alertCode, long flap) {
        RedisFlapInfo info = getRedisFlapInfo(alertCode);
        info.setFlap(flap);
        put(alertCode, JSON.toJSONString(info));
    }

    public void setTimes(String alertCode, long times) {
        RedisFlapInfo info = getRedisFlapInfo(alertCode);
        info.setTimes(times);
        put(alertCode, JSON.toJSONString(info));
    }
    
    public RedisFlapInfo getRedisFlapInfo (String alertCode) {
        String flapInfoStr = get(alertCode);
        RedisFlapInfo info = JSON.toJavaObject(JSON.parseObject(flapInfoStr), RedisFlapInfo.class);
        return info;
    }
}
